import Chart from '../chart/chart';
const FileSaver = require('file-saver');
const JSZip = require('jszip');

let config = {
  'graph1': { url: 'http://localhost:3000/graph' },
  'graph2': { url: 'http://localhost:3000/graph' },
  'graph3': { url: '' },
  'graph4': { url: '' }
};

export function download () {
  let zip = new JSZip();
  let config = Object.values(Chart.instances).reduce((a, b) => {
    a[b.key] = {url: b.url};
    return a;
  }, {});
  Object.values(Chart.instances).map((d) => {
    zip.file(d.key + '.js', createGraph(d.option, d.name));
  });
  zip.file('config.js', createConfig(config));
  zip.file('common.js', getFunctionContent(createCommon));
  zip.file('graph.vue', getFunctionContent(createGraphVue));

  // var img = zip.folder("images");
  // img.file("smile.gif", imgData, {base64: true});
  let fileName = Chart.project.name;
  zip.generateAsync({type: 'blob'})
    .then(function (content) {
      FileSaver.saveAs(content, (fileName === '' ? 'graph-code-for-vue' : fileName) + '.zip');
    });
}

function getFunctionContent (func) {
  let txt = func.toString();
  let start = txt.indexOf('/*');
  let stop = txt.lastIndexOf('*/');
  // console.log(txt.substr(start + 2, stop - start - 2));
  return txt.substr(start + 2, stop - start - 2);
}

function createConfig (config) {
  let content = 'const config = ';
  content += JSON.stringify(config, null, '\t');
  content += ';\r\nexport default config;';
  return content;
}

function createGraph (option, name) {
  let content = 'export let option = ';
  content += JSON.stringify(option, null, '\t');
  content += ";\r\nexport const name = '" + name + "';";
  return content;
}

function createCommon () {
/*
import echarts from 'echarts';
import config from './config'

let Chart = {
  config: config,
  instances: {},
  current: {id: ''},
  // 基础绘图方法
  init: function (option, id) {
    let myChart = echarts.init(document.getElementById(id));
    myChart.setOption(option);
    return myChart;
  },
  // 通用基础绘图方法
  draw: function (option, name) {
    console.log(config);
    let id = config[name].id;
    let e = Chart.init(option, id);
    Chart.instances[name] = {
      'id': id,
      'instance': e,
      'option': option
    };
    return e;
  },
  update: function (id) {
    Chart.init(Chart.instances[id].option, id);
  },
  dataLoad: DataLoad,
  ajaxData: function (key, data, _callbackS, _callbackE) {
    let cbkf = ((Math.random() * 1000).toFixed(0) + 1000).toString();
    $.ajax({
      type: 'GET',
      url: key,
      data: data,
      dataType: 'jsonp',
      jsonpCallback: 'call1back' + cbkf + 'a',
      crossDomain: true,
      success: function (data) {
        if (_callbackS) _callbackS(data);
      },
      error: function (data) {
        if (_callbackE)_callbackE(data);
        alert('error');
      }
    });
  }
};

// 图形数据加载器
let DataLoader;
DataLoader = {
  'common': function (option, data) {
    let x = [];
    let y = data.map((d) => { x.push(d.name); return d.value; });
    let xAxis = $.isArray(option.xAxis) ? option.xAxis[0] : option.xAxis;
    let ser = $.isArray(option.series) ? option.series[0] : option.series;
    xAxis['data'] = x;
    ser['data'] = y;
  },
  'pie': function (option, data) {
    let ser = $.isArray(option.series) ? option.series[0] : option.series;
    ser['data'] = data;
  },
  'pieTwo': function (option, data) {
    let legend = $.isArray(option.legend) ? option.legend[0] : option.legend;
    let colorP = option.color;
    let parents = data.map(d => ({name: d.name, value: d.value.reduce((a, b) => (a + b.value), 0)}));
    let children = data.reduce((a, b, i) => a.concat(b.value.map(e => {
      e['itemStyle'] = {color: colorP[i]};
      return e;
    })), []);
    legend['data'] = parents.map(d => d.name);
    option.series[0]['data'] = parents;
    option.series[1]['data'] = children;
  },
  'graph2': function (option, graph) {
    let legend = $.isArray(option.legend) ? option.legend[0] : option.legend;
    let groups = graph.nodes.reduce((a, b) => {
      if (!(b.category in a)) a[b.category] = 1;
      return a;
    }, {});
    let categories = graph['categories'] || Object.keys(groups).map((d) => ({'name': '类' + d}));
    let ser = $.isArray(option.series) ? option.series[0] : option.series;
    legend['data'] = categories;
    ser['data'] = graph.nodes;
    ser['links'] = graph.links;
    ser['categories'] = categories;
  }
};

function DataLoad (option, name, data) {
  const common = {'bar': 0, 'line': 0};
  let tp = name in common ? 'common' : name;
  if (!(tp in DataLoader)) return;
  DataLoader[tp](option, data);
}

export default Chart;

*/
}

function createGraphVue () {
/*
<template>
  <div class="graph-view" :id="id"></div>
</template>

<script>
import config from './config';
import Chart from './common';

export default {
  name: 'graph',
  props: {
    'value': {}
  },
  data () {
    let id = 'view' + (Math.random() * 10000).toFixed(0);
    if (this.value in config) config[this.value]['id'] = id;
    return {
      id: id,
      url: config[this.value].url
    }
  },
  mounted () {
    let $this = this;
    console.log([this.id, this.value, this.url]);
    import(`./${this.value}.js`).then(
      // 得到配置项
      function (lib) {
        // 图形配置项，图形名称
        let [option, name] = [lib.option, lib.name];
        // 无接口情况
        if (config[$this.value].url === '') {
          Chart.draw(option, $this.value);
        } else {
          Chart.ajaxData(config[$this.value].url, {}, function (rst) {
            // 数据转换接口
            Chart.dataLoad(option, name, rst.data);
            Chart.draw(option, $this.value);
          });
        }
      }
    );
  }
}
</script>

<style scoped>
  .graph-view {
    width: 100%;
    height: 100%;
    min-height: 200px;
    min-width: 200px;
  }
</style>
*/
}
